package com.min.ganymedtest;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 利用ganymed-ssh2 来实现连接ssh服务，并执行命令
 */
public class SshBasic {

    //    private static final Logger LOGGER = LoggerFactory.getLogger(SshBasic.class);
    private Connection conn;
    private static SshBasic instance;

    private SshBasic() {
    }

    public static SshBasic getInstance() {
        if (instance == null) {
            synchronized (SshBasic.class) {
                instance = new SshBasic();
            }
        }
        return instance;
    }

    /**
     * 连接ssh服务器
     *
     * @param hostname ip地址
     * @param port 端口
     * @param username 用户名
     * @param password 密码
     * @return
     */
    public Connection connect(String hostname, int port,String username, String password) {
        try {
            conn = new Connection(hostname,port);
            conn.connect();

            boolean isAuthenticated = conn.authenticateWithPassword(username, password);

            if (isAuthenticated == false)
                throw new IOException("Authentication failed.");

            System.out.println("与主机：" + hostname + "连接成功");
        } catch (IOException e) {
            System.out.println(e.getMessage() + e);
        }
        return conn;
    }

    /**
     * 执行命令
     *
     * @param command 命令字符串
     * @return
     */
    public Map<String, Object> execCommand(String command) {
        boolean flag = false;  //返回命令执行的结果
        int status = 0;
        String msg = "";
        Session sess = null;
        BufferedReader br = null;

        if (conn == null)
            throw new IllegalStateException("没有建立连接");

        System.out.println("开始执行命令：" + command);
        int length = -1;
        byte[] buffer = new byte[1024];
        long start = System.currentTimeMillis();
        StringBuilder sb = new StringBuilder();
        try {
            sess = conn.openSession();
            sess.execCommand(command);
            InputStream is = sess.getStdout();
            InputStream is_err = sess.getStderr();
            while ((length = is.read(buffer)) > -1) {
                sb.append(new String(buffer, 0, length));
            }
            while ((length = is_err.read(buffer)) > -1) {
                sb.append(new String(buffer, 0, length));
            }
            //获取执行命令后的结果返回值，0为正常，其他为不正常
            status = sess.getExitStatus();
            msg = sb.toString().substring(0,sb.toString().length()-1); // 命令执行输出

            if (sess.getExitStatus() == 0) {
                flag = true;
            }

            System.out.println("命令执行成功，耗时：秒" + (System.currentTimeMillis() - start) / 1000.0 + "秒");
        } catch (IOException e) {
            System.out.println(e.getMessage() + e);
            msg = e.getMessage();
        } finally {
            try {
                if (sess != null) {
                    sess.close();
                }
                if (null != br) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("status", status);
        result.put("msg", msg);

        return result;
    }

    /**
     * 关闭连接
     */
    public void close() {
        if (conn != null) {
            conn.close();
        }
    }


    public static void main(String[] args) {
        Map<String, Object> result;
        String hostname = "192.168.1.5";
        int port = 22;
        String username = "root";
        String password = "root";

        SshBasic instance = SshBasic.getInstance();
        instance.connect(hostname,port, username, password);

        result = instance.execCommand("docker ps");
        System.out.println(result);
        result = instance.execCommand("docker ps -a");
        System.out.println(result);
        result = instance.execCommand("echo $PATH");
        System.out.println(result);
        result = instance.execCommand("sleep 3 ; ls");
        System.out.println(result.get("msg"));


        instance.close();
    }
}
